import EventDispatcher from "../event/EventDispatcher";

export default class AssetsBundle extends EventDispatcher {

    constructor() {
        super();
        this.name = null;
        this.progress = 0;
        this._assets = [];
        this._afterMiddleware = null;
        this._beforeMiddleware = null;
    }

    getAssets() {
        return this._assets;
    }

    getBeforeMiddleware() {
        return this._beforeMiddleware;
    }

    setBeforeMiddleware(func) {
        if (func instanceof Function) {
            this._beforeMiddleware = func;
        }
    }

    getAfterMiddleware() {
        return this._afterMiddleware;
    }

    setAfterMiddleware(func) {
        if (func instanceof Function) {
            this._afterMiddleware = func;
        }
    }

    add(name, url, options, cb) {
        if (!this._checkExist(name)) {
            this._assets.push({name: name, url: url, options: options, cb: cb});
        }
        return this;
    }

    dispose() {
        this.progress = 0;
        this.removeAllEventListener();
        this._assets = [];
        this._afterMiddleware = null;
        this._beforeMiddleware = null;
    }

    reset() {
        this.progress = 0;
        this._assets = [];
        this._afterMiddleware = null;
        this._beforeMiddleware = null;
    }

    _checkExist(name) {
        for (let i = 0, l = this._assets.length; i < l; ++i) {
            if (name === this._assets[i].name) {
                return true;
            }
        }
        return false;
    }
}